package com.css.fxfzdzzh.modules.evaluate.controller;


import com.alibaba.fastjson.JSONObject;
import com.css.fxfzdzzh.base.response.RestResponse;
import com.css.fxfzdzzh.modules.drill.service.DrillService;
import com.css.fxfzdzzh.modules.eqLandslide.count.service.EqLandslideService;
import com.css.fxfzdzzh.modules.eqLandslide.count.vo.StatisticsAreaVO;
import com.css.fxfzdzzh.modules.evaluate.VO.*;
import com.css.fxfzdzzh.modules.evaluate.entity.SoftSoilResult;
import com.css.fxfzdzzh.modules.evaluate.entity.TaskVersion;
import com.css.fxfzdzzh.modules.evaluate.entity.ValuatePage;
import com.css.fxfzdzzh.modules.evaluate.service.SoftSoilService;
import com.css.fxfzdzzh.modules.hypergraph.service.HypergraphService;
import com.css.fxfzdzzh.util.PlatformObjectUtils;
import com.css.fxfzdzzh.util.PlatformPageUtils;
import com.css.fxfzdzzh.util.ResponseCreator;
import com.css.fxfzdzzh.zcpt.sys.service.SysAreaService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author Dbj
 * @date 2023年02月14日  15:08
 */
@RestController
@RequestMapping("/softSoil")
public class SoftSoilController {

    @Value("${basicData.url}")
    public String basicDataUrl;
    //private static final String SJXTRESTURL = "http://10.13.155.124:8087/fxfzsjxt";

    @Resource
    private SoftSoilService softSoilService;

    @Resource
    private DrillService drillService;

    @Resource
    RestTemplate restTemplate;

    @Resource
    SysAreaService sysAreaService;

    @Resource
    HypergraphService hypergraphService;

    @Resource
    EqLandslideService eqLandslideService;

    /***
     * 评估列表查询
     * @param vo
     * @return
     */
    @GetMapping("/page")
    public RestResponse getPage(SoftSoilQueryVO vo, HttpServletRequest request){
        int curPage = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
        int pageSize=Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
        Map<String,Object> page=softSoilService.getPage(vo,curPage,pageSize);
        return ResponseCreator.createSuccessResponse(page);
    }
    /***
     * 分页获取版本信息
     * @param param
     * @return
     */
    @GetMapping("/versionPage")
    public RestResponse versionPage(DrillVersionVO param) throws UnsupportedEncodingException {
        String dataRangeCountry = "";
        String dataRangeProvince = "";
        String provinceName = param.getProvince();
        if(StringUtils.isNotBlank(provinceName)){
            String[] array = provinceName.split(",");
            List<String> provinceList = Arrays.asList(array);
            List<String> provinceNameList = new ArrayList<>();//省
            Set<String> set = new HashSet<>();
            provinceList.forEach(str->{
                String[] split = str.split("-");
                set.add(split[0]);
                provinceNameList.add(split[0]);
            });

            if(set.size()>1){
                //跨省
                dataRangeCountry = "1";
            }else{
//                provinceName = URLEncoder.encode(provinceName,"UTF-8");
//                String id = sysAreaService.getIdByCondition(provinceName, "", "");
                String province = provinceNameList.get(0);
                province = URLEncoder.encode(province,"UTF-8");
                String id = sysAreaService.getIdByCondition(province, "", "");
                dataRangeProvince = id.split("_")[0];
            }
        }
        String url = basicDataUrl + "/datacenter/sysDataVersion/page?dataRangeCountry="+dataRangeCountry+"&dataRangeProvince="+dataRangeProvince+"&hasNationwide=1";
        if(StringUtils.isNotBlank(param.getVersionDesc())){
            url += "&versionDesc="+param.getVersionDesc();
        }
        if(StringUtils.isNotBlank(param.getVersionCode())){
            url += "&versionCode="+param.getVersionCode();
        }
        if(StringUtils.isNotBlank(param.getUploadUser())){
            url += "&uploadUsername="+param.getUploadUser();
        }
        if(StringUtils.isNotBlank(param.getUploadStartTime())){
            url += "&uploadStartTime="+param.getUploadStartTime();
        }
        if(StringUtils.isNotBlank(param.getUploadEndTime())){
            url += "&uploadEndTime="+param.getUploadEndTime();
        }
        return drillService.getJCSJ(url,2);
    }

    /***
     * 为任务保存选择的钻孔数据版本
     */
    @PostMapping("/saveTaskDrillVersion")
    public RestResponse saveTaskDrillVersion(@RequestBody  TaskVersion taskVersion){
        String versionCode = softSoilService.saveTaskDrillVersion(taskVersion);
        return ResponseCreator.createSuccessResponse(versionCode,"保存成功");
    }

    /***
     * 评估
     */
    @PostMapping("/evaluate")
    public RestResponse evaluate(@RequestBody EvaluateVO vo){
        List<SoftSoilResult> list = softSoilService.evaluate(vo);
        if (list.size()>0) {
            //刷新指定超图工作空间数据源数据集
            boolean bool = hypergraphService.getWorkspaceReload("dzzh_soft_soil_evaluate_result");
        }
        return ResponseCreator.createSuccessResponse(list,"评估完成");
    }

    /***
     * 保存为中间结果
     */
    @PostMapping("/saveToCenterResult")
    public RestResponse saveToCenterResult(@RequestBody EvaluateVO vo){
        softSoilService.saveToCenterResult(vo);
        return ResponseCreator.createSuccessResponse("保存中间结果成功");
    }

    /***
     * 评估页面数据默认展示
     */
    @GetMapping("/getEvaluatePage")
    public RestResponse getEvaluatePage(@NotBlank(message = "任务id不能为空")String taskId,String dtcvId){
        ValuatePage page = softSoilService.getEvaluatePage(taskId,dtcvId);
        return ResponseCreator.createSuccessResponse(page);
    }

    /***
     * 中间结果列表查询
     * @param taskId
     * @return
     */
    @GetMapping("/getCenterDataPage")
    public RestResponse getCenterDataPage(String taskId, HttpServletRequest request){
        int curPage = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
        int pageSize=Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
        Map<String,Object> page=softSoilService.getCenterDataPage(taskId,curPage,pageSize);
        return ResponseCreator.createSuccessResponse(page);
    }

    /***
     * 将中间结果设置为最终结果
     */
    @PostMapping("/saveToFinalResult")
    public RestResponse saveToFinalResult(@RequestBody EvaluateVO vo){
        softSoilService.saveToFinalResult(vo);
        return ResponseCreator.createSuccessResponse("替换为最终结果成功");
    }

    /***
     * 删除中间结果
     */
    @PostMapping("/deleteCenterVersion")
    public RestResponse deleteCenterVersion(@RequestBody Map<String,String> map){
        softSoilService.deleteCenterVersion(map);
        return ResponseCreator.createSuccessResponse("删除成功");
    }

    /**
     * 导入钻孔数据
     */
    @PostMapping("/importDrillData/{taskId}/{versionCode}")
    public RestResponse importDrillData(@PathVariable("taskId") String taskId,@PathVariable(value = "versionCode",required = false) String versionCode, @RequestParam("file") MultipartFile file, HttpServletResponse response){
       RestResponse restResponse = softSoilService.importDrillData(taskId,versionCode, file, response);
       if (200==restResponse.getCode()){
           restResponse.setMessage("导入成功");
       }
        return restResponse;
    }

    /**
     * 批量保存软土震陷区域计算结果
     */
    @PostMapping("/savePolygonEvaluateResult")
    public RestResponse savePolygonEvaluateResult(@RequestBody List<PolygonEvaluateResultVO> voList){
        softSoilService.savePolygonEvaluateResult(voList);
        if (voList.size()>0) {
            //刷新指定超图工作空间数据源数据集
            boolean bool = hypergraphService.getWorkspaceReload("dzzh_soft_soil_polygon_evaluate_result");
        }
        return ResponseCreator.createSuccessResponse("","区域计算成功");
    }

    //按省统计危险性面积（【软土震陷】分析评估结果）
    @PostMapping("/countResultAreaByProvince")
    public RestResponse countResultAreaByProvince(@RequestBody Map<String,String> map) {
        RestResponse restResponse=null;
        try {
            restResponse=softSoilService.countResultAreaByProvince(map.get("taskId"));
            if (restResponse.getCode() == 200) {
                restResponse.setMessage("按省统计危险性面积成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("按省统计危险性面积失败！");
        }
        return restResponse;
    }

    //按市统计危险性面积（【软土震陷】分析评估结果）
    @PostMapping("/countResultAreaByCity")
    public RestResponse countResultAreaByCity(@RequestBody Map<String,String> map) {
        RestResponse restResponse=null;
        try {
            restResponse=softSoilService.countResultAreaByCity(map.get("taskId"));
            if (restResponse.getCode() == 200) {
                restResponse.setMessage("按市统计危险性面积成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("按市统计危险性面积失败！");
        }
        return restResponse;
    }

    /***
     * 大屏获取全国地震地质灾害概况
     * @return
     */
    @GetMapping("/getCountAreaResult")
    public RestResponse getCountAreaResult(){
        JSONObject js = softSoilService.getCountAreaResult();
        return ResponseCreator.createSuccessResponse(js);
    }

    @PostMapping("/exportExcel")
    public void exportExcel(@RequestBody Map<String,String> paramaMap, HttpServletResponse response) throws Exception {
        String taskId = paramaMap.get("taskId");
        String modelId = paramaMap.get("modelId");
        String intensity = paramaMap.get("intensity");
        String modelType = paramaMap.get("modelType");
        Map<String, List<StatisticsAreaVO>> map = eqLandslideService.getStatisticsAreaForExport(intensity,modelId,taskId,modelType);
        java.lang.String templateName = "";
        int cellSize = 0;
        String path =  ResourceUtils.getURL("classpath:template/excel/").getPath();
        if("软土震陷".equals(modelType)){
            templateName = path+"软土震陷危险性面积.xlsx";
            cellSize = 5;
        }else{
            templateName = path+"危险性面积.xlsx";
            cellSize = 11;
        }
        File file = new File(templateName);
        XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(file));
        XSSFCellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        XSSFFont font = workbook.createFont();
        font.setFontHeightInPoints((short) 12);
        style.setFont(font);
        style.setBorderBottom(BorderStyle.THIN); // 下边框
        style.setBorderLeft(BorderStyle.THIN);//左边框
        style.setBorderTop(BorderStyle.THIN);//上边框
        style.setBorderRight(BorderStyle.THIN);//右边框
        //省
        List<StatisticsAreaVO> provinceList = map.get("0");
        if(PlatformObjectUtils.isNotEmpty(provinceList) && provinceList.size()>0){
            buildCellData(workbook, cellSize,"按省统计危险性面积",provinceList,style,modelType);
        }
        //市
        List<StatisticsAreaVO> cityList = map.get("1");
        if(PlatformObjectUtils.isNotEmpty(cityList) && cityList.size()>0){
            buildCellData(workbook, cellSize+1,"按市统计危险性面积",cityList,style,modelType);
        }
        //区县
        List<StatisticsAreaVO> countyList = map.get("2");
        if(PlatformObjectUtils.isNotEmpty(countyList) && countyList.size()>0){
            countyList = countyList.stream().filter(statisticsAreaVO -> PlatformObjectUtils.isNotEmpty(statisticsAreaVO.getProvince()) && !"中华人民共和国".equals(statisticsAreaVO.getProvince())).collect(Collectors.toList());
            buildCellData(workbook, cellSize+2,"按区县统计危险性面积",countyList,style,modelType);
        }

        BufferedOutputStream fos = null;
        try{
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String( file.getName().getBytes("gb2312"), "ISO8859-1" ));
            fos = new BufferedOutputStream(response.getOutputStream());
            workbook.write(fos);
        }finally {
            if (fos != null) {
                fos.close();
            }
        }
    }


    private void buildCellData(XSSFWorkbook  workbook,int cellSize,String sheetName, List<StatisticsAreaVO> list,XSSFCellStyle style,String modelType){
        Sheet sheet = workbook.getSheet(sheetName);
        for (int i = 0; i < list.size(); i++) {
            int h = 0;
            Row row = sheet.createRow(i+2);
            StatisticsAreaVO statisticsAreaVO = list.get(i);
            Cell cell = row.createCell(h++);
            cell.setCellValue(statisticsAreaVO.getProvince());
            cell.setCellStyle(style);
            if("软土震陷".equals(modelType)){
                if(cellSize==6){
                    cell = row.createCell(h++);
                    cell.setCellValue(statisticsAreaVO.getCity());
                    cell.setCellStyle(style);
                }
                if(cellSize==7){
                    cell = row.createCell(h++);
                    cell.setCellValue(statisticsAreaVO.getCity());
                    cell.setCellStyle(style);
                    cell = row.createCell(h++);
                    cell.setCellValue(statisticsAreaVO.getCounty());
                    cell.setCellStyle(style);
                }
                cell = row.createCell(h++);
                cell.setCellValue(PlatformObjectUtils.isNotEmpty(statisticsAreaVO.getZxArea())?statisticsAreaVO.getZxArea()+"":"");
                cell.setCellStyle(style);
                cell = row.createCell(h++);
                cell.setCellValue(PlatformObjectUtils.isNotEmpty(statisticsAreaVO.getZxRatio())?statisticsAreaVO.getZxRatio()+"":"");
                cell.setCellStyle(style);
                cell = row.createCell(h++);
                cell.setCellValue(PlatformObjectUtils.isNotEmpty(statisticsAreaVO.getBzxArea())?statisticsAreaVO.getBzxArea()+"":"");
                cell.setCellStyle(style);
                cell = row.createCell(h++);
                cell.setCellValue(PlatformObjectUtils.isNotEmpty(statisticsAreaVO.getBzxRatio())?statisticsAreaVO.getBzxRatio()+"":"");
                cell.setCellStyle(style);
            }else{
                if(cellSize==12){
                    cell = row.createCell(h++);
                    cell.setCellValue(statisticsAreaVO.getCity());
                    cell.setCellStyle(style);
                }
                if(cellSize==13){
                    cell = row.createCell(h++);
                    cell.setCellValue(statisticsAreaVO.getCity());
                    cell.setCellStyle(style);
                    cell = row.createCell(h++);
                    cell.setCellValue(statisticsAreaVO.getCounty());
                    cell.setCellStyle(style);
                }
                cell = row.createCell(h++);
                cell.setCellValue(PlatformObjectUtils.isNotEmpty(statisticsAreaVO.getEhArea())?statisticsAreaVO.getEhArea()+"":"");
                cell.setCellStyle(style);
                cell = row.createCell(h++);
                cell.setCellValue(PlatformObjectUtils.isNotEmpty(statisticsAreaVO.getEhRatio())?statisticsAreaVO.getEhRatio()+"":"");
                cell.setCellStyle(style);
                cell = row.createCell(h++);
                cell.setCellValue(PlatformObjectUtils.isNotEmpty(statisticsAreaVO.getHArea())?statisticsAreaVO.getHArea()+"":"");
                cell.setCellStyle(style);
                cell = row.createCell(h++);
                cell.setCellValue(PlatformObjectUtils.isNotEmpty(statisticsAreaVO.getHRatio())?statisticsAreaVO.getHRatio()+"":"");
                cell.setCellStyle(style);
                cell = row.createCell(h++);
                cell.setCellValue(PlatformObjectUtils.isNotEmpty(statisticsAreaVO.getMArea())?statisticsAreaVO.getMArea()+"":"");
                cell.setCellStyle(style);
                cell = row.createCell(h++);
                cell.setCellValue(PlatformObjectUtils.isNotEmpty(statisticsAreaVO.getMRatio())?statisticsAreaVO.getMRatio()+"":"");
                cell.setCellStyle(style);
                cell = row.createCell(h++);
                cell.setCellValue(PlatformObjectUtils.isNotEmpty(statisticsAreaVO.getLArea())?statisticsAreaVO.getLArea()+"":"");
                cell.setCellStyle(style);
                cell = row.createCell(h++);
                cell.setCellValue(PlatformObjectUtils.isNotEmpty(statisticsAreaVO.getLRatio())?statisticsAreaVO.getLRatio()+"":"");
                cell.setCellStyle(style);
                cell = row.createCell(h++);
                cell.setCellValue(PlatformObjectUtils.isNotEmpty(statisticsAreaVO.getElArea())?statisticsAreaVO.getElArea()+"":"");
                cell.setCellStyle(style);
                cell = row.createCell(h++);
                cell.setCellValue(PlatformObjectUtils.isNotEmpty(statisticsAreaVO.getElRatio())?statisticsAreaVO.getElRatio()+"":"");
                cell.setCellStyle(style);
            }
        }
    }

    //按区县统计危险性面积（【软土震陷】分析评估结果）
    @PostMapping("/countResultAreaByCounty")
    public RestResponse countResultAreaByCounty(@RequestBody Map<String,String> map) {
        RestResponse restResponse=null;
        try {
            restResponse=softSoilService.countResultAreaByCounty(map.get("taskId"));
            if (restResponse.getCode() == 200) {
                restResponse.setMessage("按区县统计危险性面积成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("按区县统计危险性面积失败！");
        }
        return restResponse;
    }

}
